<template>
  <div class="">
    <div class="flex items-center mb-2">
      <h3 class="flex-1 text-lg font-medium text-gray-800">{{ title }}</h3>
      <el-button type="primary" size="small" @click="handleAdd">
        {{ addButtonText || t('添加') }}
      </el-button>
      <el-button type="primary" size="small" @click="handleRemove">
        {{ t('删除') }}
      </el-button>
    </div>

    <el-table :data="modelValue" border class="mb-4" :empty-text="emptyText" size="small">
      <el-table-column type="selection" width="32"/>
      <el-table-column
          v-for="column in columns"
          :key="column.prop"
          :label="column.label"
          :width="column.width || 'auto'"
          :min-width="column.minWidth"
      >
        <template #default="{ row, $index }">
          <component
                     :is="getComponent(column.type)"
              :row="row"
              :column="column"
              :index="$index"
              @update="handleUpdate($index, column.prop, $event)"
          />
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import TableInput from './TableInput.vue'
import TableSelect from './TableSelect.vue'
import TableComplex from './TableComplex.vue'
import {useI18n} from "vue-i18n";
import TableInner from "@/views/BatteryPassport/components/TableInner.vue";

const {t} = useI18n()

const props = defineProps({
  title: String,
  modelValue: Array,
  columns: Array,
  addButtonText: String,
  removeButtonText: String,
  actionLabel: String,
  actionWidth: String,
  emptyText: String,
  showActions: {
    type: Boolean,
    default: true
  },
  defaultItem: null
})

const emit = defineEmits(['add', 'remove', 'update'])

const getComponent = (type) => {
  const components = {
    input: TableInput,
    select: TableSelect,
    complex: TableComplex,
    table: TableInner
  }
  return components[type] || TableInput
}

const handleAdd = () => {
  const newItem = JSON.parse(JSON.stringify(props.defaultItem))
  props.modelValue.push(newItem)
}

const handleUpdate = (index, prop, value) => {
  emit('update', {index, prop, value})
}

const handleRemove = (index) => {
  props.modelValue.splice(index, 1)
  emit('remove', index)
}
</script>

<style scoped>
</style>